//
//  BiBaseNetEngine.m
//  TrunkIndustryManageSystem
//
//  Created by bindu on 15-4-7.
//  Copyright (c) 2015年 李璐西. All rights reserved.
//

#import "BiBaseNetEngine.h"
#import "BiNetEngine.h"
#import "ASINetworkQueue.h"
#import "ASIFormDataRequest.h"


@implementation BiBaseNetEngine

- (id)init
{
    if (self = [super init])
    {
        _networkQueue = [[ASINetworkQueue alloc] init];
        [_networkQueue setDelegate:self];
        [_networkQueue setRequestDidFinishSelector:NSSelectorFromString(@"requestDone:")];
        [_networkQueue setRequestDidFailSelector:NSSelectorFromString(@"requestFaild:")];
        
        _dataDic = [[NSMutableDictionary alloc] init];
    }
    
    return self;
}

- (void)dealloc
{
    [_networkQueue cancelAllOperations];
    [_networkQueue reset];
//    [_networkQueue release];
//    
//    _RELEASE(_dataDic)
//    
//    [super dealloc];
}

- (NSString *)urlEncodeValue:(NSString *)str
{
    NSString *result = (NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, NULL, kCFStringEncodingUTF8));
    //return [result autorelease];
    return result;
}


- (NSString *)sendJson:(NSDictionary *)dictionary
{
    NSMutableString *jsonText = [[NSMutableString alloc] initWithString:@"{"];
    for (id key in dictionary)
    {
        [jsonText appendFormat:@"\"%@\":\"%@\",",key,[dictionary objectForKey:key]];
    }
    NSString *str = [jsonText substringToIndex:jsonText.length - 1];
    str = [NSString stringWithFormat:@"%@}",str];
    return str;
}
- (NSString *)sendJsonFromArr:(NSArray *)Array
{
   
    NSMutableString *allText = [[NSMutableString alloc] initWithString:@"["];
    
    for (NSDictionary * dictionary in Array) {
        
        NSMutableString *jsonText = [[NSMutableString alloc] initWithString:@"{"];
        for (id key in dictionary)
        {
            [jsonText appendFormat:@"\"%@\":\"%@\",",key,[dictionary objectForKey:key]];
        }
        NSString *str = [jsonText substringToIndex:jsonText.length - 1];
        str = [NSString stringWithFormat:@"%@},",str];
        
        [allText appendString:str];
    }
    
     NSString *endstr = [allText substringToIndex:allText.length - 1];
    
    endstr = [NSString stringWithFormat:@"%@]",endstr];
    
    return endstr;
}


- (ASIFormDataRequest *)createPostRequest:(NSString *)url_ paramDic:(NSDictionary*)paramDic tag:(int)tag
{
    NSString *url = [self urlEncodeValue:url_];
    
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request setRequestMethod:@"POST"];
    [request addRequestHeader:@"Content-Type" value:@"application/x-www-form-urlencoded;charset=UTF-8"];
    [request addRequestHeader:@"connection" value:@"keep-alive"];
    NSString * token = [BiUserEntity sharedInstance].access_token;
    
    if (token) {
        
       [request addRequestHeader:@"Authorization" value:token];
        
    }
    
    
  //  [request addRequestHeader:@"Connection" value:@"keep-alive"];
    
    if (nil != paramDic)
    {
        NSString * paraStr = [self sendJson:paramDic];
//        
 //      [request appendPostData:[str dataUsingEncoding:NSUTF8StringEncoding]];
  //      [request setPostBody:[str dataUsingEncoding:NSUTF8StringEncoding]];
        
//        for (int i = 0; i < paramDic.allKeys.count; i++)
//        {
//            [request addPostValue:[paramDic objectForKey:[paramDic.allKeys objectAtIndex:i]] forKey:[paramDic.allKeys objectAtIndex:i]];
//        }
        
        NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:paraStr
                               ,@"params", nil];
        for (int i = 0; i < dict.allKeys.count; i++)
        {
            [request addPostValue:[dict objectForKey:[dict.allKeys objectAtIndex:i]] forKey:[dict.allKeys objectAtIndex:i]];
        }
    }
    
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:[NSString stringWithFormat:@"%d",tag] forKey:@"t_tag"];
    [request setUserInfo:userInfo];
    [request setTimeOutSeconds:SERVICE_TIMEOUT];
    [_networkQueue addOperation:request];
    
    [_networkQueue go];
    NSLog(@"%@     tag:%d", url_, tag);
    NSLog(@"%@", request);
    
   // return [request autorelease];
    return request;
}


- (ASIFormDataRequest *)createPostRequest:(NSString *)url_ paramArr:(NSArray*)paramArr tag:(int)tag
{
    NSString *url = [self urlEncodeValue:url_];
    
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request setRequestMethod:@"POST"];
    [request addRequestHeader:@"Content-Type" value:@"application/x-www-form-urlencoded;charset=UTF-8"];
    [request addRequestHeader:@"connection" value:@"keep-alive"];
    NSString * token = [BiUserEntity sharedInstance].access_token;
    
    if (token) {
        
        [request addRequestHeader:@"Authorization" value:token];
        
    }
    
    if (nil != paramArr)
    {
        NSString * paraStr = [self sendJsonFromArr:paramArr];
        
        NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:paraStr
                               ,@"params", nil];
        
        for (int i = 0; i < dict.allKeys.count; i++)
        {
            [request addPostValue:[dict objectForKey:[dict.allKeys objectAtIndex:i]] forKey:[dict.allKeys objectAtIndex:i]];
        }
    }
    
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:[NSString stringWithFormat:@"%d",tag] forKey:@"t_tag"];
    [request setUserInfo:userInfo];
    
    [request setTimeOutSeconds:SERVICE_TIMEOUT];
    
    [_networkQueue addOperation:request];
    
    [_networkQueue go];
    
    return request;
}


- (ASIFormDataRequest *)createPutRequest:(NSString *)url_ paramDic:(NSDictionary*)paramDic tag:(int)tag
{
    NSString *url = [self urlEncodeValue:url_];
    
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request setRequestMethod:@"POST"];
    [request addRequestHeader:@"Content-Type" value:@"application/x-www-form-urlencoded;charset=UTF-8"];
    [request addRequestHeader:@"connection" value:@"keep-alive"];
    NSString * token = [BiUserEntity sharedInstance].access_token;
    
    if (token) {
        
        [request addRequestHeader:@"Authorization" value:token];
        
    }
    
    if (nil != paramDic)
    {
        NSString * paraStr = [self sendJson:paramDic];
        
        NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:paraStr
                               ,@"params", nil];
        
        for (int i = 0; i < dict.allKeys.count; i++)
        {
            [request addPostValue:[dict objectForKey:[dict.allKeys objectAtIndex:i]] forKey:[dict.allKeys objectAtIndex:i]];
        }
    }
    
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:[NSString stringWithFormat:@"%d",tag] forKey:@"t_tag"];
    [request setUserInfo:userInfo];
    
    [request setTimeOutSeconds:SERVICE_TIMEOUT];
    
    [_networkQueue addOperation:request];
    
    [_networkQueue go];

    return request;
}

- (ASIFormDataRequest *)createPostImageRequest:(NSString *)url_ image:(UIImage*)image paraDic:(NSDictionary *)paraDic tag:(int)tag
{
    NSString *url = [self urlEncodeValue:url_];
    
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request setRequestMethod:@"POST"];
    
    [request addRequestHeader:@"Accept-Encoding" value:@"gzip, deflate"];
    [request addRequestHeader:@"Content-Type" value:@"multipart/form-data,charset=UTF-8"];
    [request addRequestHeader:@"Connection" value:@"keep-alive"];
    [request setPersistentConnectionTimeoutSeconds:60];
     NSString * token = [BiUserEntity sharedInstance].access_token;
    if (token) {
        
        [request addRequestHeader:@"Authorization" value:token];
        
    }
    
    [request setShouldStreamPostDataFromDisk:YES];
    
    NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
    NSString * imageFileName = [BiUtil getSendTmpFileName:paraDic];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:imageFileName])
    {
        [fileManager removeItemAtPath:imageFileName error:nil];
    }
    
    if([imageData writeToFile:imageFileName atomically:YES]){
    
        NSLog(@"write YEW");
    };
   // [request addPostValue:@"1" forKey:@"Type"];
    [request setFile:imageFileName forKey:@"params"];
    
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:[NSString stringWithFormat:@"%d",tag] forKey:@"t_tag"];
    [request setUserInfo:userInfo];
    
    [request setTimeOutSeconds:SERVICE_TIMEOUT_UP];
    [_networkQueue addOperation:request];
    
    NSLog(@"%@     tag:%d", url_, tag);
    [_networkQueue go];
    
    //return [request autorelease];
    return request;
}

- (ASIHTTPRequest *)createGetRequest:(NSString *)url_ paramDic:(NSDictionary*)paramDic tag:(int)tag
{
    NSString *url = [self urlEncodeValue:url_];
    
    if (nil != paramDic)
    {
        if (paramDic.allKeys.count > 0)
        {
            NSMutableString * mutableString = [NSMutableString stringWithFormat:@"?"];
            
            for (int i = 0; i < paramDic.allKeys.count; i++)
            {
                NSString * key = [paramDic.allKeys objectAtIndex:i];
                NSString * value = [paramDic objectForKey:[paramDic.allKeys objectAtIndex:i]];
                [mutableString appendFormat:@"%@=%@&", key, value];
            }
            
            NSString * paramString = [mutableString substringToIndex:(mutableString.length-1)];
            url = [NSString stringWithFormat:@"%@%@", url, paramString];
        }
    }
    
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:url]];
    request.useCookiePersistence = YES;
    [request setRequestMethod:@"GET"];
    
    NSString * token = [BiUserEntity sharedInstance].access_token;
    
    if (token) {
        
        [request addRequestHeader:@"Authorization" value:token];
        
    }
    
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:[NSString stringWithFormat:@"%d",tag] forKey:@"t_tag"];
    [request setUserInfo:userInfo];
    [request setTimeOutSeconds:SERVICE_TIMEOUT];
    [_networkQueue addOperation:request];
    
    [_networkQueue go];
    //return [request autorelease];
    return request;
}



//    *****************      网络处理      *****************
#pragma mark ASI Request
-(void)requestFaild:(ASIHTTPRequest *)request
{
    int tag = [[[request userInfo] objectForKey:@"t_tag"] intValue];
    NSLog(@"%@---tag: %d",[[request error] description], tag);
    
    id delegate = [_dataDic objectForKey:[NSNumber numberWithInt:tag]];
    [_dataDic removeObjectForKey:[NSNumber numberWithInt:tag]];  // 请求完后清除掉delegate
    
    if (nil != delegate && [delegate respondsToSelector:@selector(onNetEngineResponseFail:entity:userInfo:)])
    {
        [delegate onNetEngineResponseFail:tag entity:nil userInfo:nil];
    }
}

- (void)requestDone:(ASIHTTPRequest *)request
{
    assert(0);
}





@end
